import useAuth, { UseAuthCallbackProp } from "@/hooks/useAuth"
import { DeleteOutlined, FormOutlined, LeftOutlined, PlusOutlined, RightOutlined, SearchOutlined, UnorderedListOutlined } from "@ant-design/icons";
import { ProChat } from '@ant-design/pro-chat';
import { Button, Card, Col, Divider, Flex, Input, Layout, message, Modal, 
  Popconfirm, Popover, Row, Space, Tooltip, Typography, Form} 
  from "antd";
import { useEffect, useRef, useState } from "react";
import styles from "./index.module.less";
import { useLocation } from "umi";
import Scrollbars from "react-custom-scrollbars-2";
import PromptInputArea from "@/components/PromtInputArea";
import AiDocService from "@/services/ai_doc/aidoc";
const { Title, Text } = Typography;
const { Header, Sider, Content } = Layout;

const conversationData = [
  {
    id: "123",
    title: "标题1",
    description: "描述",
  },
  {
    id: "124",
    title: "标题2",
    description: "描述",
  },
]

const suffix = (
  <SearchOutlined
    className={styles['button-item']}
    style={{
      fontSize: 16,
    }}
  />
);

const initChatsEq = [
  {
    content: '你是谁？',
    createAt: 1697862242452,
    id: 'ZGxiX2p4',
    role: 'user',
    updateAt: 1697862243540,
  },
  {
    content: '请回复我！我要生气了！',
    createAt: 1697862242453,
    id: 'ZGxiX2JQ',
    role: 'user',
    updateAt: 1697862243540,
  },
  {
    content: `我怎么知道我是谁！`,
    createAt: 1697862242458,
    id: 'Sb5pAzLL',
    role: 'assistant',
    updateAt: 1697862243540,
  },
]



const AiDoc = ()=> {

  const [openList, setOpneList] = useState(false)
  const [currentConversation, setCurrentConversation] = useState<any>(null)
  const [hoverConversation, setHoverConversation] = useState<any>(null)
  const [openUpdateConversaionModal, setOpenUpdateConversationModal] = useState<boolean>(false)
  const [loading, setLoading] = useState(false);
  const [initChats, setInitChats] = useState<any>([]);
  const [conversationList, setConversationList] = useState<any>([])
  const [form] = Form.useForm();

  const currentUpdateConversationRef = useRef<any>(null)
  const [currentUpdateConversationState, setCurrentUpdateConversationState] = useState<any>({})
  
  const formItemLayout = { labelCol: { span: 4 }, wrapperCol: { span: 14 } }

  const checkLogin = (data: UseAuthCallbackProp) => {
    if (!data.isLogin) {
      message.info('未登录账号，该功能将无法正常使用');
    }
  }
  const location = useLocation();
  
  useAuth({loadFinishedCallback: checkLogin});
  
  const checkConversationId = () => {
    if (!currentConversation?.id) {
      message.error("对话id异常")
      return false
    }
    return true
  }

  const proChatRequestHook = async (messages: any) => {
    if (!checkConversationId()) {
      return;
    }
    // const response = await AppHttp.fetchHttpWithStream(AppConstant.UMI_BASE_URL + "/api/ai-doc/chat-stream", {
    //   method: "POST",
    //   headers: {
    //     'Content-Type': 'application/json;charset=UTF-8',
    //   },
    //   body: JSON.stringify({prompt: messages[messages.length - 1]?.message}),
    // })
    const response = await AiDocService.aiDocStreamChat({prompt: messages[messages.length - 1]?.message
      , conversationId: currentConversation.id ? currentConversation.id : ""
    })
    // 确保服务器响应是成功的
    if (!response) {
      return undefined;
    }
    // 获取 reader
    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    const encoder = new TextEncoder();

    const readableStream = new ReadableStream({
      async start(controller) {
        function push() {
          reader
            .read()
            .then(({ done, value }) => {
              if (done) {
                controller.close();
                return;
              }
              const chunk = decoder.decode(value, { stream: true });
              const message = chunk.replace('data:', '').trim();
              let parsed = null;
              try {
                parsed = JSON.parse(message);
              } catch (err) {
                push()
                return;
              }
              const content = parsed.output.choices[0].message.content
              controller.enqueue(encoder.encode(content));
              push();
            })
            .catch((err) => {
              controller.error(err);
            });
        }
        push();
      },
    });
    return new Response(readableStream);
  }

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const inputRenderer = (_: React.ReactNode,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    onMessageSend: (message: string) => void | Promise<any>,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    onClear: () => void) => {
    return <PromptInputArea inputProp={{placeholder:"请输入想要了解的内容"}}
      handleSend={(content: string) => {onMessageSend(content)}}
    ></PromptInputArea>
  }

  const loadCurrentConversationHistory = async (id: string | null) => {
    if (id === null || id.length === 0) {
      return;
    }
    // 请求当前对话数据，骨架屏过渡加载中
    setLoading(true)
    const res = await AiDocService.loadHistoryConversationMessage({id})
    console.log("page res: ", res)
    if (res) {
      setInitChats(res)
    }
    setLoading(false)
  }

  const loadHistoryConversationList = async () => {
    // 请求API 加载历史对话记录列表
    console.log("加载历史对话记录列表")
    const resp = await AiDocService.loadHistoryConversation({page: 1, pageSize: 1000})
    setConversationList(resp?.data)
    // 检查是否指定了加载的历史对话
    const params = new URLSearchParams(location.search);
    loadCurrentConversationHistory(params.get("id"));
  }

  useEffect(() => {
    loadHistoryConversationList();
  }, [])

  const handleClickConversationItem = (item: any) => {
    setCurrentConversation(item)
    loadCurrentConversationHistory(item.id)
    // 后续有空优化添加和URL匹配的对话记录
    // const searchParams = new URLSearchParams()
    // searchParams.set("id", item.id)
    // history.replace({
    //   pathname: location.pathname,
    //   search: `?${searchParams.toString()}`
    // });
  }

  const handleClickDeleteConversationInfo = async (item: any) => {
    // TODO 删除对话信息
    AiDocService.deleteConversationInfo({id: item.id}).then(() => {
      loadHistoryConversationList()
    })
  }

  const handleClickUpdateConversationInfo = (item: any) => {
    console.log("更新: ", item)
    currentUpdateConversationRef.current = {...item}
    setCurrentUpdateConversationState({...item})
    setOpenUpdateConversationModal(true)
    form.resetFields()
  }

  const handleConfirmUpdateConversation = async (data: any) => {
    if (!data) {
      return;
    }
    // TODO 更新对话信息
    console.log("更新当前对话信息", data, form, currentUpdateConversationRef.current)
    const req = {id: currentUpdateConversationRef.current.id, ...data}
    AiDocService.updateConversationInfo(req).then(() => {
      console.log("更新对话信息完成")
      loadHistoryConversationList()
    })
    setOpenUpdateConversationModal(false)
  }

  const handlelickCreateConversation = async () => {
    await AiDocService.createConversationInfo({})
    loadHistoryConversationList()
  }

  const handleCancelUpdateConversation = () => {
    currentUpdateConversationRef.current = null
    setOpenUpdateConversationModal(false)
  }

  return (
      <Layout style={{ background: "#f5f5f5", padding: '5px', height: '100%', borderRadius: '5px'}}>
        <Sider width={'20%'} style={{backgroundColor: '#ececec', padding: '5px'}} collapsed={openList} collapsedWidth={0}>
          <Row style={{padding: '5px'}}>
            <Col span={21}>
              <Input width={'100%'} placeholder="搜索对话" suffix={suffix} size="large"/>
            </Col>
            <Col span={3} style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
              <Tooltip title="创建新对话">
                <Button onClick={() => {handlelickCreateConversation()}} size="large" type="link">
                  <PlusOutlined style={{fontSize: '24px'}}/>
                </Button>
              </Tooltip>
            </Col>
          </Row>
          <Divider style={{marginTop: '5px', marginBottom: '5px'}}></Divider>
          <Scrollbars
                style={{ height: '90%' }}
                renderThumbVertical={({ ...props }) => (
                  <div
                    {...props}
                    style={{
                      backgroundColor: '#faad14', // 滚动条颜色
                      borderRadius: '4px', // 滚动条圆角
                    }}
                  />
                )}
                autoHide
              >
              <Flex vertical style={{overflow: "hidden"}}>
                {conversationList?.map((item: any) => (
                    <Card 
                      key={item.id}
                      style={{
                        margin: '5px',
                        backgroundColor: currentConversation?.id === item.id ? 'rgb(255, 207, 92)' : 'white'
                      }} 
                      onClick={() => {handleClickConversationItem(item)}}
                      hoverable
                      onMouseOver={() => {setHoverConversation(item)}}
                      onMouseOut={()=>{setHoverConversation(null)}}
                    >
                      {item.title}
                      
                      { 
                      hoverConversation?.id === item.id && 
                        <Popover content={
                        <Space direction="vertical">
                            <Space className={styles['list-item']} onClick={() => {handleClickUpdateConversationInfo(item)}}>
                              <FormOutlined />
                              <Text>修改</Text>
                            </Space>
                            <Space className={styles['list-item']}>
                              <Popconfirm
                                title="删除该对话数据"
                                description="将会删除该对话的所有历史数据，不可恢复！！！"
                                onConfirm={() => handleClickDeleteConversationInfo(item)}
                                okText="是"
                                cancelText="否"
                              >
                                <Space>
                                  <DeleteOutlined style={{color: 'red'}}/> 
                                  <Text>删除</Text>
                                </Space> 
                              </Popconfirm>
                            </Space>
                          </Space>}>
                          <UnorderedListOutlined style={{
                            position: "absolute",
                            right: '15px',
                            color: 'black'
                          }}/>
                        </Popover>
                      }
                    </Card>
                ))}
            </Flex>
          </Scrollbars>
          
        </Sider>
        <Layout style={{backgroundColor: '#f5f5f5'}}>
          <Header style={{backgroundColor: 'white', padding: '0 16px 0 16px'}}>
            <Row >
              <Col span={1} >
                <Button onClick={() => {setOpneList(openList ? false : true)}} style={{marginLeft: 0}}>
                  {openList ? <RightOutlined /> : <LeftOutlined />}  
                </Button>
              </Col>
              <Col span={23} style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                <Title level={5}>{currentConversation?.title}</Title>
              </Col>
            </Row>
          </Header>
          <Content >
            {currentConversation !== null ? <ProChat
              loading={loading}
              helloMessage={
                '欢迎使用文案助手，这里可以为您提供文本问答帮助哦！！！'
              }
              request={proChatRequestHook}
              chats={initChats}
              // inputAreaRender={()=>{return <></>}}
              inputAreaRender={inputRenderer}
              style={{height: '100%'}}
            />
            :
            <Card style={{height: '100%'}}>
            </Card>

            }
          </Content>
        </Layout>
        <Modal title="更新对话信息" open={openUpdateConversaionModal} 
          onOk={handleConfirmUpdateConversation}
          onCancel={handleCancelUpdateConversation}
          footer={null}
          >
            <Form
              {...formItemLayout}
              form={form}
              onFinish={handleConfirmUpdateConversation}
              initialValues={currentUpdateConversationState}
            >
              <Form.Item label="标题" name="title">
                <Input placeholder="输入标题" />
              </Form.Item>
              <Form.Item label="描述" name="description">
                <Input placeholder="输入描述" />
              </Form.Item>
              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button type="primary" htmlType="submit">
                  更新
                </Button>
              </Form.Item>
            </Form>
        </Modal>
      </Layout>
  );
}

export default AiDoc;
